package com.ruoyi.loan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.loan.dto.LoanApplyDto;
import com.ruoyi.loan.dto.PoorStudentApplyDto;
import com.ruoyi.loan.dto.SelectUserListDto;
import com.ruoyi.loan.dto.UpdateUserMessageDto;
import com.ruoyi.loan.entity.LoanRecord;
import com.ruoyi.loan.entity.PoorApplyRecord;
import com.ruoyi.loan.entity.User;
import com.ruoyi.loan.mapper.ImageMapper;
import com.ruoyi.loan.mapper.LoanRecordMapper;
import com.ruoyi.loan.mapper.PoorApplyMapper;
import com.ruoyi.loan.mapper.UserMapper;
import com.ruoyi.loan.service.UserService;
import com.ruoyi.loan.utils.*;
import com.ruoyi.loan.vo.LoanRecordDetailVo;
import com.ruoyi.loan.vo.LoanRecordVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @Author lin
 * @Date 2022/4/5 0:17
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService  {

    private static final String VALIDATE_ING = "正在审核";
    private static final String VALIDATE_ACCESS = "审核通过";
    private static final String VALIDATE_REFUSE = "审核不通过";

   @Autowired
   private UserMapper userMapper;

   @Autowired
   private LoanRecordMapper loanRecordMapper;

   @Resource
   private HttpServletRequest request;

   @Autowired
   private PoorApplyMapper poorApplyMapper;

   @Autowired
   private ImageMapper imageMapper;

   @Autowired
   private FileUtils fileUtils;

    @Override
    public PageInfo getMyLoanRecord(int pageNum, int pageSize) {

        HttpSession session = request.getSession();
        User user = null;
        Object attribute = session.getAttribute(session.getId());
        if (attribute == null){
            throw new RuntimeException("用户登录已失效，请重新登录");
        }
        user = (User)attribute;

        // 进行pageHelper分页查询
        PageHelper.startPage(pageNum,pageSize);
        List<LoanRecordVo> loanRecordVos = loanRecordMapper.getMyLoanRecord(user.getId());
        PageInfo<LoanRecordVo> pageInfo = new PageInfo<>(loanRecordVos);
        List<LoanRecordVo> list = pageInfo.getList();
        // 处理一下状态转换
        for (LoanRecordVo recordVo : list){
            int state = recordVo.getStatus();
            if (state == 1){
                recordVo.setValidateMessage(VALIDATE_ING);
            }else if(state == 2){
                recordVo.setValidateMessage(VALIDATE_ACCESS);
            }else {
                recordVo.setValidateMessage(VALIDATE_REFUSE);
            }
        }
        return pageInfo;
    }

    @Override
    public LoanRecordDetailVo getLoanRecordDetails(int id) {

        // 校验id的合法性
        if (id <1){
            throw new RuntimeException("查询参数无效");
        }
        //查询详情
        LoanRecordDetailVo loanDetails = loanRecordMapper.getLoanRecordDetailsById(id);
        // 状态变化
        if (loanDetails == null){
            return null;
        }
        int state = loanDetails.getStatus();
        if (state == 1){
            loanDetails.setValidateMessage(VALIDATE_ING);
        }else if(state == 2 ){
            loanDetails.setValidateMessage(VALIDATE_ACCESS);
        }else {
            loanDetails.setValidateMessage(VALIDATE_REFUSE);
        }
        return loanDetails;
    }

    @Override
    public void loanApply(LoanApplyDto loanApplyDto) {
        User user = null;
        //获取用户的id
        HttpSession session = request.getSession();
        Object attribute = session.getAttribute(session.getId());
        if (attribute == null){
            throw new RuntimeException("登录失效，请重新登录");
        }
        user = (User)attribute;
        LoanRecord loanRecord = new LoanRecord();
        BeanUtils.copyProperties(loanApplyDto,loanRecord);
        Integer userId = user.getId();
        LoanRecord loanRecordFromDB = loanRecordMapper.selectByUserIdAndYear(userId, Calendar.getInstance().get(Calendar.YEAR));
        if (loanRecordFromDB != null) {
            throw new RuntimeException("今年已提交过申请，请勿重复申请");
        }
        loanRecord.setUserId(userId);
        loanRecord.setStatus(1);
        loanRecord.setOwingAmount(loanApplyDto.getAmount());
        int result = loanRecordMapper.insert(loanRecord);
        if (result < 1){
            throw new RuntimeException("提交贷款申请失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void poorStudentApply(PoorStudentApplyDto poorStudentApplyDto) {
        User user = null;
        //获取用户的id
        HttpSession session = request.getSession();
        Object attribute = session.getAttribute(session.getId());
        if (attribute == null){
            throw new RuntimeException("登录失效，请重新登录");
        }
        user = (User)attribute;
        PoorApplyRecord poorApplyRecordFromDB = poorApplyMapper.selectByUserIdAndYear(user.getId(),Calendar.getInstance().get(Calendar.YEAR));
        if (poorApplyRecordFromDB != null) {
            throw new RuntimeException("今年已提交过申请，请勿重复申请");
        }

        PoorApplyRecord poorApplyRecord = new PoorApplyRecord();
        BeanUtils.copyProperties(poorStudentApplyDto,poorApplyRecord);
        poorApplyRecord.setUserId(user.getId());
        poorApplyRecord.setYear(new Date().getYear());
        poorApplyRecord.setStatus(1);
        int result = poorApplyMapper.insert(poorApplyRecord);
        if (result <1){
            throw new RuntimeException("申请提交失败，请重试");
        }
        // 进行贫困图片的处理
        List<Integer> imageIds = poorStudentApplyDto.getImageIds();

        if (!imageIds.isEmpty()){
           int update = imageMapper.updateImagekeyId(imageIds,poorApplyRecord.getId());
        }
    }

    @Override
    public void updateUserMessage(UpdateUserMessageDto updateUserMessageDto) {
        // 获取用户信息
        User user = null;
        HttpSession session = request.getSession();
        Object attribute = session.getAttribute(session.getId());
        if (attribute == null){
            throw new RuntimeException("登录失效，请重新登录");
        }
        user = (User)attribute;

        // 校验数据的准确性
        String phone = updateUserMessageDto.getPhone();

        if (StringUtils.isNotEmpty(phone)){
            boolean flag = CheckPhoneUtils.checkPhone(phone);
            if ( !flag){
                throw new RuntimeException("手机号不合法");
            }
        }

        String idCard = updateUserMessageDto.getIdCard();

        if (StringUtils.isNotEmpty(idCard)){
            boolean flag = CheckIdentityCard.checkIdentityCard(idCard);
            if ( !flag){
                throw new RuntimeException("身份证号不合法");
            }
        }

        String mail = updateUserMessageDto.getMail();

        if (StringUtils.isNotEmpty(mail)){
            boolean flag = CheckMailUtils.validEmail(mail);
            if ( !flag){
                throw new RuntimeException("邮箱不合法");
            }
        }

//        // 是否有文件上传
//        MultipartFile multipartFile = updateUserMessageDto.getMultipartFile();
//        if (multipartFile != null){
//            // 进行文件上传
//            boolean flag = FileUtils.checkFileSize(multipartFile);
//            if ( !flag){
//                throw new RuntimeException("文件超出约束限制");
//            }
//            String path = FileUtils.upLoadFile(multipartFile, FileUtils.LOAN_IMG);
//            userObj.setAvatarUrl(path);
//        }
        user = userMapper.selectById(user.getId());

        String avatar = updateUserMessageDto.getAvatarUrl();
        if (StringUtils.isNotEmpty(avatar)){
            user.setAvatarUrl(avatar);
        }
        Integer classNo = updateUserMessageDto.getClassNo();
        if (classNo != null){
            user.setClassNo(classNo);
        }
        String gender = updateUserMessageDto.getGender();
        if (StringUtils.isNotEmpty(gender)) {
            user.setGender(gender);
        }
        Integer grade = updateUserMessageDto.getGrade();
        if (grade != null){
            user.setGrade(grade);
        }
        user.setIdCard(idCard);
        user.setMail(mail);
        user.setPhone(phone);
        String major = updateUserMessageDto.getMajor();
        if (StringUtils.isNotEmpty(major)){
            user.setMajor(major);
        }
        String username = updateUserMessageDto.getUsername();
        if (StringUtils.isNotEmpty(username)){
            user.setUsername(username);
        }
        int result = userMapper.updateById(user);
        if (result < 1){
            throw new RuntimeException("个人信息更新失败");
        }
        //更新session中的用户信息
        if (user.getAvatarUrl() != null){
            user.setAvatarUrl(fileUtils.getShowFilePath(user.getAvatarUrl()));
        }
        session.setAttribute(session.getId(),user);
    }

    @Override
    public PageInfo selectUserList(SelectUserListDto selectUserListDto) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();

        String username = selectUserListDto.getUsername();
        if (StringUtils.isNotEmpty(username)){
            queryWrapper = queryWrapper.like("username","%" + username + "%");
        }
        if (StringUtils.isNotEmpty(selectUserListDto.getPhone())){
            queryWrapper = queryWrapper.like("phone", "%" + selectUserListDto.getPhone() + "%");
        }
        if (StringUtils.isNotEmpty(selectUserListDto.getMail())){
            queryWrapper = queryWrapper.like("mail", "%" + selectUserListDto.getMail() + "%");
        }
        if (StringUtils.isNotEmpty(selectUserListDto.getCollege())){
            queryWrapper = queryWrapper.like("college", "%" + selectUserListDto.getCollege() + "%");
        }
        if (StringUtils.isNotEmpty(selectUserListDto.getMajor())){
            queryWrapper = queryWrapper.like("major", "%" + selectUserListDto.getMajor() + "%");
        }
        if (selectUserListDto.getGrade() != null){
            queryWrapper = queryWrapper.eq("grade",  selectUserListDto.getGrade());
        }
        if (selectUserListDto.getClassNo() != null){
            queryWrapper = queryWrapper.eq("class_no", selectUserListDto.getClassNo());
        }
        if (StringUtils.isNotEmpty(selectUserListDto.getIdCard())){
            queryWrapper = queryWrapper.like("id_card", "%" + selectUserListDto.getIdCard() + "%");
        }
        if (StringUtils.isNotEmpty(selectUserListDto.getGender())){
            queryWrapper = queryWrapper.eq("gender", selectUserListDto.getGender());
        }

        PageHelper.startPage(selectUserListDto.getPageNum(),selectUserListDto.getPageSize());
        List<User> users = userMapper.selectList(queryWrapper);

        return new PageInfo<>(users);
    }

    @Override
    public void updatePassword(Integer userId, String password) {
        if (!PasswordUtils.checkPasswordLength(password)){
            throw new RuntimeException("密码不可为空，至少9位数");
        }
        String salt = PasswordUtils.getEncryptionSalt();
        String encryptionPassword = PasswordUtils.getEncryptionPassword(password, salt);
        User user = userMapper.selectById(userId);
        if (user == null){
            throw new RuntimeException("用户信息不存在");
        }
        user.setPassword(encryptionPassword);
        user.setSalt(salt);
        userMapper.updateById(user);
    }

    @Override
    public PageInfo myPoorApplyList(Integer userId) {
        List<PoorApplyRecord> poorApplyRecordList = poorApplyMapper.selectList(new QueryWrapper<PoorApplyRecord>().eq("user_id", userId));
        return new PageInfo(poorApplyRecordList);
    }

    public User selectUserById(Integer userId){
        return userMapper.selectById(userId);
    }
}
